package com.cyz.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyz.config.RabbitConfig;
import com.cyz.dao.ProductDao;
import com.cyz.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ProductDao productDao;

    @GetMapping("/test")
    public String test(){
        rabbitTemplate.convertAndSend(RabbitConfig.WORK_DIRECTEXCHANGE, RabbitConfig.WORK_DIRECTROUTING, "测试上传至RabbitMQ");
        return "over";
    }

    @GetMapping("/start/{total}")
    public String start(@PathVariable int total){
        Product product = productDao.selectOne(new QueryWrapper<Product>().eq("product_name", "iPhone 14 Pro Max"));
        if (product == null){
            product = new Product();
            product.setProductName("iPhone 14 Pro Max");
            product.setTotal(total);
            productDao.insert(product);
        }else {
            product.setTotal(total);
            productDao.updateById(product);
        }
        for (int i = 0; i < total; i++){
            rabbitTemplate.convertAndSend(RabbitConfig.WORK_DIRECTEXCHANGE, RabbitConfig.WORK_DIRECTROUTING, JSONObject.toJSONString(product));
            log.info("生产消息成功");
        }
        return "生成成功";
    }
}
